package com.naiterui.common.redis.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息序列化Util
 */
public class SerializeUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SerializeUtil.class);

    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            LOGGER.warn("Object serialize WARING : errMsg = {}", e);
        }
        return null;
    }

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        if (bytes == null) {
            return null;
        }
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
            return ois.readObject();
        } catch (StreamCorruptedException | EOFException sce) {
            LOGGER.warn("Object serialize type dismarch WARING : errMsg = {}", sce.getMessage());
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            LOGGER.warn("Object serialize WARING : errMsg = {}", e.getMessage());
        }
        return null;
    }
}
